define([
    "dojo/_base/declare",
    "gistech/widgets/normalDialog/NormalDialog",
    "dojo/text!./templates/Template.html",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dojo/on",
    "dojo/_base/connect",
    "gistech/util/ajaxUtil",
    "dojo/dom-style","dojo/query","dojo/dom-class",],
    function(declare,NormalDialog,template,lang,style,domConstruct,on,eventconnect,ajaxUtil,domStyle,query,domClass){
        return declare([NormalDialog],{
        	
            templateString:template,
            container:null,
            resetAttr:function(){
                this.inherited(arguments);
            },

            constructor:function (args) {
            	this.inherited(arguments);
            	this.container = args.container;
            	this.companyNode=null,
            	this.businessNode=null,
            	this.developmentNode=null,
            	
            	//
               	this.allVehicleData = new Object();
                this.map = args.map;
                this.container = args.container;
                this.currentPage=1;
                this.totalPage=1;
                this.currentSource=[];
            },
            
            postCreate:function(){
                this.inherited(arguments);
                //domConstruct.place(this.domNode, this.container);
                this.init();
                this.addEvents();

            },

            /**
             * 初始化
             */
            init:function () {
                this.companyNode=dojo.byId('company');
                this.businessNode=dojo.byId('business');
                this.developmentNode=dojo.byId('development');
            	this.loadData(true,true);
            	this.getOrganizationData(0,1);
            },
            
            
            addEvents:function(){
//            	topic.subscribe("ChangeArrowDirection", lang.hitch(this, this.ChangeArrowDirection));
            	on(dojo.byId('name'),"keypress",dojo.hitch(this,this.nameKeyPress));
            	on(this.btnOk,"click",dojo.hitch(this,this.loadData));
            },
            
            nameKeyPress:function(e){
            	if(e.keyCode==13){
            		this.loadData();
            	}
            	
            },
            
            /*
             * 加载数据
             */
            loadData:function(bCanClick,bShowLoading){
            	var userName= dojo.byId('name').value;
                	ajaxUtil.request("../client/service/userOrganizationController/queryUserAll","userName="+userName+"&rows=11&page=1",lang.hitch(this,function(result){
            		this.allVehicleData=lang.clone(result);
                	this.currentSource=this.allVehicleData.rows;
    	    		var len=this.allVehicleData.total;
    	    		var firstlen=len>10?10:len;
                	this._inittable(this.currentSource,0,firstlen);
                	this._initpager(len);
            	}),function(){
                    console.error("获取人员数据失败");
                });
                	
                	
                	
            },
            
            /*
             * 初始化表头
             */
            _inittableHeader:function(){
            	return '<tr><th style="width:38px">序号</th><th style="width:80px">登录名</th><th style="width:86px">姓名</th><th style="width:85px">集团/公司</th><th style="width:85px">事业部</th><th style="width:85px">扩展组</th><th style="width:60px">编制满员率</th><th style="width:60px">编制限额</th><th style="width:68px">操作</th> </tr>';
            },
            
            /*
             * 初始化表格
             */
            _inittable:function(source,firstnum,endnum){
            	
            	this.gridtable.innerHTML="";
                var html="";
            	var headerHtml=this._inittableHeader();
            	html+=headerHtml;
            	var num = 0;
            	
            	for (var i=firstnum;i<endnum;i++){
        			var user=source[i];
        			html+="<tr><td>"+(++num)+' </td><td>'+user.userName+'</td><td>'+user.displayName+'</br><td>'+user.organizationCompanyName+'</td><td>'+user.organizationBusinessName+'</td><td>'+user.organizationDevelopName+'</td><td>'+user.quotaPercent+'</td><td>'+user.quota+'</td><td><a class="updateUser">修改</a></td><td style="display:none">'+user.userId+'</td>';
        			
        			if(user.organizationCompanyName==undefined && user.organizationBusinessName==undefined && user.organizationDevelopName==undefined){
        				html+='<td style="display:none" id='+"exist"+user.userId+'>0</td>'
        			}else{
        				html+='<td style="display:none" id='+"exist"+user.userId+'>1</td>'
        			}
        			
        			html+="</tr>";//style="display:nono"
        		}
            	html=html.replace(/undefined/g,'');
            	this.gridtable.innerHTML=html;
            	on(dojo.query('a.updateUser'),"click",dojo.hitch(this,this.updateUser));
 
            },
            
            /*
             * 初始化分页
             */
            _initpager:function(len,startPage,endPager){
            	startPage=startPage||1;
            	endPager=endPager||15;
            	this.pager.innerHTML="";
            	domStyle.set(this.pager, "display", "block");
            	var html='<li><<</li><li><</li><li class="selectpager">'+startPage+'</li>';
            	
            	this.totalPage=parseInt((len-0.5)/10)+1;
            	if (this.totalPage<=15){
            		for (var i=2;i<=this.totalPage;i++){
                		html+='<li>'+i+'</li>';
                	}
            	}
            	else{
            		for (var i=startPage+1;i<=endPager;i++){
                		html+='<li>'+i+'</li>';
                	}
            	}
            	html+='<li>></li><li>>></li>';
            	this.pager.innerHTML=html;

            	query(".data-list ul.pager li").forEach(lang.hitch(this,function(node,index){
            		on(node, 'click', lang.hitch(this,function (){
            			 switch (node.textContent)
            			 {
            			      case "<<":
            			    	  if (this.currentPage==1) return;
            			    	  this.currentPage=1;
            			    	  this._inittable(this.currentSource,0,10);
            			    	  
            			    	  if (this.currentPage>=startPage){
            			    		  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==2) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }else{
            			    		  this._initpager(len);
            			        	  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==2) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }
            			    	  break;
            			      case "<":
            			    	  if (this.currentPage==1) return;
            			    	  this.currentPage--;
            			    	  var firstNum=(this.currentPage-1)*10;
            			    	  var lastNum=this.currentPage*10;
            			    	  this._inittable(this.currentSource,firstNum,lastNum);
            			    	  
            			    	  if (this.currentPage>=startPage){
            			    		  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==(2+this.currentPage-startPage)) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }else{
            			    		  this._initpager(len,startPage-1,endPager-1);
            			        	  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==2) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			    	  }
            			    	  break;
            			      case ">":
            			    	  if (this.currentPage==this.totalPage) return;
            			    	  this.currentPage++;
            			    	  var firstNum=(this.currentPage-1)*10;
            			    	  var lastNum=this.currentPage*10;
            			          if (this.currentPage==this.totalPage)
            			        	  lastNum=this.currentSource.length;
            			          this._inittable(this.currentSource,firstNum,lastNum);
            			          if (this.currentPage<=endPager){
            			        	  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==(1+this.currentPage)) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			          }else{
            			        	  this._initpager(len,startPage+1,endPager+1);
            			        	  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==16) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
            			          }
            			    	  break;
            			      case ">>":
            			    	  if (this.currentPage==this.totalPage) return;
            			    	  this.currentPage=this.totalPage;
            			    	  
            			    	  var firstNum=(this.currentPage-1)*10;
            			          var lastNum=this.currentSource.length;
        			    	      this._inittable(this.currentSource,firstNum,lastNum);
        			    	      
        			    	      if (this.currentPage<=endPager){
        			    	    	  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==(1+this.totalPage)) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
        			    	      }
        			    	      else{
        			    	    	  this._initpager(len,this.totalPage-14,this.totalPage);
        			    	    	  query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
                			    		  if (index==16) domClass.add(temnode, "selectpager");
                			    		  else domClass.remove(temnode, "selectpager");
            			    	      }));
        			    	      }
            			    	  break;
            			      default:
            			    	  this.currentPage=node.textContent;
            			          var firstNum=(this.currentPage-1)*10;
            			          var lastNum=this.currentPage*10;
            			          if (node.textContent==this.totalPage)
            			        	  lastNum=this.currentSource.length;
        			    	      this._inittable(this.currentSource,firstNum,lastNum);
        			    	      
        			    	      query(".data-list ul.pager li").forEach(lang.hitch(this,function(temnode,index){
        			    	    	  domClass.remove(temnode, "selectpager");
        			    	      }));
        			    	      domClass.add(node, "selectpager");
            			    	  break;
            			 }
            		}));
            	}));
            },
            
            updateUser:function(e){
            	var flag = e.target.innerText;
        		var parent = e.target.parentNode.parentNode;//tr
            	var loginName = e.target.parentNode.parentNode.children[1];
            	var name = e.target.parentNode.parentNode.children[2];
            	var company = e.target.parentNode.parentNode.children[3];
            	var business =e.target.parentNode.parentNode.children[4];
            	var develop =e.target.parentNode.parentNode.children[5];
            	var userId =e.target.parentNode.parentNode.children[9].innerText;
            	if(flag=='修改'){
                	var tempTd = document.createElement("td");
                	var tempTd2 = document.createElement("td");
                	var tempTd3 = document.createElement("td");
                	
                	var c= this.companyNode.cloneNode(true);
                	c.id='1'+userId;
                	c.style.display='block'
                	tempTd.appendChild(c);
                	 
                	var b= this.businessNode.cloneNode(true);
                	b.id='2'+userId;
                	b.style.display='block'
                	tempTd2.appendChild(b);
                	
                	var d= this.developmentNode.cloneNode(true);
                	d.id='3'+userId;
                	d.style.display='block'
                	tempTd3.appendChild(d);
                	
                	parent.replaceChild(tempTd,company)
                	parent.replaceChild(tempTd2,business)
                	parent.replaceChild(tempTd3,develop)
                	e.target.innerText='确定	';
                	
                	on(dojo.byId(c.id),'change',dojo.hitch(this,this.loadSelect))
                	on(dojo.byId(b.id),'change',dojo.hitch(this,this.loadSelect))
            	}else{
            		
            		var cValue = company.childNodes[0].value;
            		var bValue = business.childNodes[0].value;
            		var dValue = develop.childNodes[0].value;
            		var existFlag =e.target.parentNode.parentNode.children[10].innerText;
            		
            		var param = "id="+userId+"&companyId="+cValue+"&businessId="+bValue+"&developId="+dValue+"&existFlag="+existFlag;
            		this.updateUserOrganization(param);
            		
            	}
            	 
            },
            
            loadSelect:function(e){
            	var value = e.target.value;
                ajaxUtil.request("../client/service/userOrganizationController/getOrganization","parentId="+value,lang.hitch(this,function(result){
                    var Store = eval(result.result);
                     var StoreHTML = "<option selected=\"selected\" value=\"\">请选择</option>";
                     for(var i=0; i<Store.length;i++){
                         StoreHTML += "<option value='"+Store[i].id+"'>"+Store[i].organizationName+"</option>";
                     }
                     if(e.target.attributes[3].value==1){
                    	 dojo.byId('2'+e.target.id.substr(1)).innerHTML = StoreHTML;
                     }else if(e.target.attributes[2].value==2){
                    	 dojo.byId('3'+e.target.id.substr(1)).innerHTML = StoreHTML;
                     }
                    	 
                    
                 }),function(){
                    console.error("获取下拉列表失败");
                 });
            	
            },
            
            updateUserOrganization:function(param){
            	if(param!=''){
                	ajaxUtil.request("../client/service/userOrganizationController/updateUserOrganization",param,lang.hitch(this,function(result){
                		if(result.success){
                			this.loadData();
                		}else{
                			alert('更新失败');
                		}
                	}),function(){
                		alert('更新失败');
                        console.error("更新人员数据失败");
                    });
            	}

            },
            
            getOrganizationData:function(parentId,type){
            	
                ajaxUtil.request("../client/service/userOrganizationController/getOrganization","parentId="+parentId,lang.hitch(this,function(result){
                    var Store = eval(result.result);
                     var StoreHTML = "<option selected=\"selected\" value=\"\">请选择</option>";
                     for(var i=0; i<Store.length;i++){
                         StoreHTML += "<option value='"+Store[i].id+"'>"+Store[i].organizationName+"</option>";
                     }
                     if(type==1){
                    	 this.company.innerHTML = StoreHTML;
                     }
                    
                 }),function(){
                    console.error("获取下拉列表失败");
                 });
 

            },
            
            
            startup:function(){
                this.inherited(arguments);
            },
            closeDialog:function(){
    			this.inherited("closeDialog",arguments);
    			this.destroy();
    		}

    });
});

